package com.hundsun.yr.universal.p2p.widget;

import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.View;


/**
 * @Title: AdaptiveViewPager.java 
 * @Description: 能自适应高度的ViewPager
 * @date 2015-12-25 下午2:11:52 
 * @author:hejun.shen
 * @email:shenhj15971@hundsun.com 
 * @replace author:
 * @replace date:
 * @version V1.0
 */
public class AdaptiveViewPager extends ViewPager {

	public AdaptiveViewPager(Context context) {
		super(context);
	}

	public AdaptiveViewPager(Context context, AttributeSet attrs) {
		super(context, attrs);
	}


	@Override
	protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
		
		super.onMeasure(widthMeasureSpec, heightMeasureSpec);

        View view = getChildAt(0);
        if (view != null) {
            view.measure(widthMeasureSpec, heightMeasureSpec);
        }
        setMeasuredDimension(getMeasuredWidth(), measureHeight(heightMeasureSpec, view));
	}
	
	
	/**
	 * 计算View的高度
	 * @param measureSpec
	 * @param view
	 * @return
	 */
	private int measureHeight(int measureSpec, View view) {
        int result = 0;
        int specMode = MeasureSpec.getMode(measureSpec);
        int specSize = MeasureSpec.getSize(measureSpec);

        if (specMode == MeasureSpec.EXACTLY) {
            result = specSize;
        } else {
            // set the height from the base view if available
            if (view != null) {
                result = view.getMeasuredHeight();
            }
            if (specMode == MeasureSpec.AT_MOST) {
                result = Math.min(result, specSize);
            }
        }
        return result;
    }


}